const DEV = false;

const env = "prod-8g6k5cfre7cd634b";
// const env = "prod-4gl93hq66bb6eca8"

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    icon: "none",
  });
}

function getService(uri) {
  if (DEV) {
    const regex = /^\/(product|role)\b/i;
    if (regex.test(uri)) {
      return "product";
    }
    return "user";
  } else {
    const regex = /^\/(product|role)\b/i;
    if (regex.test(uri)) {
      return "product-manager";
    }
    return "user-manager";
  }
}

function getUuid() {
  if (typeof crypto === "object") {
    if (typeof crypto.randomUUID === "function") {
      return crypto.randomUUID();
    }
    if (
      typeof crypto.getRandomValues === "function" &&
      typeof Uint8Array === "function"
    ) {
      const callback = (c) => {
        const num = Number(c);
        return (
          num ^
          (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))
        ).toString(16);
      };
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, callback);
    }
  }
  let timestamp = new Date().getTime();
  let perforNow =
    (typeof performance !== "undefined" &&
      performance.now &&
      performance.now() * 1000) ||
    0;
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    let random = Math.random() * 16;
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0;
      timestamp = Math.floor(timestamp / 16);
    } else {
      random = (perforNow + random) % 16 | 0;
      perforNow = Math.floor(perforNow / 16);
    }
    return (c === "x" ? random : (random & 0x3) | 0x8).toString(16);
  });
}

/**
 * 封装 callContainer 调用逻辑
 * @param {string} uri 接口路径
 * @param {string} method 请求方式
 * @param {object} data 请求数据
 * @returns {Promise} 返回Promise对象
 */
function callContainerApi(uri, method, data) {
  console.log(getService(uri)+"\/"+uri)
  return wx.cloud.callContainer({
    config: {
      env: env,
    },
    path: uri,
    header: {
      "X-WX-SERVICE": getService(uri),
      "content-type": "application/json",
    },
    method: method || "GET",
    data: data,
  });
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
    icon: "success",
  });
}

function testMobile(num) {
  if (DEV) return true;
  var myreg =
    /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(16[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
  if (num.length == 0) {
    wx.showToast({
      title: "手机号为空",
      image: "/images/icon/icon_error.png",
    });
    return false;
  } else if (num.length < 11) {
    wx.showToast({
      title: "手机号长度有误！",
      image: "/images/icon/icon_error.png",
    });
    return false;
  } else if (!myreg.test(num)) {
    wx.showToast({
      title: "手机号有误！",
      image: "/images/icon/icon_error.png",
    });
    return false;
  } else {
    return true;
  }
}

function updateCartBadge() {
  const cartList = wx.getStorageSync("cartList") || [];
  const totalCount = cartList.length;

  if (totalCount > 0) {
    wx.setTabBarBadge({
      index: 1,
      text: totalCount.toString(),
    });
  } else {
    wx.removeTabBarBadge({
      index: 1,
    });
  }
}

function padZero(num) {
  return num < 10 ? "0" + num : num;
}

function formatTime(timestamp) {
  if (!timestamp) return "";

  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1);
  const day = padZero(date.getDate());
  const hour = padZero(date.getHours());
  const minute = padZero(date.getMinutes());

  return `${year}-${month}-${day} ${hour}:${minute}`;
}

function offsetDay(timestamp) {
  if(!timestamp) return ""
  const offsetDay = new Date(timestamp)
  return `${offsetDay.getFullYear()}-${offsetDay.getMonth()+1}-${offsetDay.getDay()} ${23}:${59}`
}

function pay(price, orderId, onSuccess) {
  wx.cloud.callFunction({
    name: "cloudbase_module",
    data: {
      // 工作流ID, 需从工作流属性中获取
      name: "sywxzfapifqzf_6bd7f03",
      data: {
        description: "商品支付",
        out_trade_no: orderId,
        amount: {
          total: Math.round(price * 100),
          currency: "CNY",
        },
      },
    },
    success: (res) => {
      console.log("下单结果: ", res);
      // 获取到预付单信息
      const paymentData = res.result?.data;
      // 唤起微信支付组件，完成支付
      wx.requestPayment({
        timeStamp: paymentData?.timeStamp,
        nonceStr: paymentData?.nonceStr,
        package: paymentData?.packageVal,
        paySign: paymentData?.paySign,
        signType: "RSA", // 该参数为固定值
        success(res) {
          // 支付成功回调，实现自定义的业务逻辑
          console.log("唤起支付组件成功：", res);
          if (typeof onSuccess === "function") onSuccess(res);
        },
        fail(err) {
          // 支付失败回调
          console.error("唤起支付组件失败：", err);
        },
      });
    },
  });
}

// 数字补零

module.exports = {
  showErrorToast,
  showSuccessToast,
  testMobile,
  updateCartBadge,
  formatTime,
  callContainerApi,
  getUuid,
  pay,
  offsetDay
};
